package com.hlw.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController {

	
	@RequestMapping("/home")
	public String index(){
		return "/home";
	}
	@RequestMapping("/login")
	public String login(){
		return "/login";
	}
	 // 这里如果不写method参数的话，默认支持所有请求，如果想缩小请求范围，还是要添加method来支持get, post等等某个请求。
	//登录方法
	 @RequestMapping(value="/ajaxlogin",method=RequestMethod.POST)	 
	 public String toLogin( String loginname,String password,Model model){
		 
	    UsernamePasswordToken token =new UsernamePasswordToken(loginname,password);
	    Subject subject = SecurityUtils.getSubject();
	    try {
	      //这里直接使用shiro的登录方法
	      subject.login(token);
	      return "/home";
	     //登录失败时，会catch到你的异常，异常通过全局处理
	    } catch (UnknownAccountException e) {
	      model.addAttribute("msg","该账号不存在");       
	    } catch (IncorrectCredentialsException e) {
	    	System.out.println(e);
	      model.addAttribute("msg","密码错误，请重试");     
	    } catch (LockedAccountException e) {
	      model.addAttribute("msg","该账户已被锁定,请联系管理员");
	    } catch (Exception e) {
	      model.addAttribute("msg","登录失败");
	    }
	    return "login";
	  }
    @RequestMapping("/403")
    public String unauthorizedRole(){
        System.out.println("------没有权限-------");
        return "403";
    }
}
